package com.wiscamp.ninechapters.problems.infrastructure.mappers.types;

import com.wiscamp.ninechapters.problems.infrastructure.po.types.QuestionTypeView;
import com.wiscamp.ninechapters.problems.infrastructure.po.types.TypeRelationPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 题型及问题类型关联数据访问对象
 *
 * @author yifeng
 */
@Repository
public interface TypeRelationMapper extends JpaRepository<TypeRelationPO, Long>, JpaSpecificationExecutor<TypeRelationPO> {
    @Query(value = "select e from TypeRelationPO e where e.problemTypeId = :problemTypeId and e.questionTypeId = :questionTypeId")
    TypeRelationPO findTypeRelation(long problemTypeId, long questionTypeId);

    @Modifying
    @Transactional
    @Query(value = "delete from TypeRelationPO e where e.problemTypeId = :problemTypeId and e.questionTypeId = :questionTypeId")
    void deleteTypeRelation(long problemTypeId, long questionTypeId);

    @Query(value = "select e.questionTypeId from TypeRelationPO e where e.problemTypeId = :problemTypeId")
    Collection<Long> findQuestionTypeIdsByProblemType(long problemTypeId);

    @Query(value = "select q from QuestionTypeView q, TypeRelationPO tr where q.typeId = tr.questionTypeId and tr.problemTypeId = :problemTypeId and q.deleted = false")
    Collection<QuestionTypeView> findQuestionTypesByProblemType(long problemTypeId);
}